<template>
  <div v-loading="loading">
    <el-table ref="tableRef" :data="records" :empty-text="$t('gridpannel.index.dataNo')" :header-cell-style="{
      background: '#fafafa',
      color: '#262626',
      height: '54px'
    }" :row-style="{
  height: '68px'
}" cell-class-name="app-table-cell app-table-line"
              element-loading-text="Loading"
              header-cell-class-name="app-table-head table-head-center"
              highlight-current-row stripe v-bind="$attrs">
      <slot></slot>
    </el-table>
    <pagination v-show="total > 0" :limit="limit" :page="page" :total="total" class="es-pagination"
                @pagination="getTableData"/>
  </div>
</template>

<script setup>
import Pagination from "@/components/es-pagination/index.vue";
import lodash from "lodash";
import Sortable from "sortablejs";
import {nextTick, onMounted, reactive, watch, ref, unref, toRefs} from 'vue'
import {useApiStore} from '@/stores/modules/apiStore/apiStore'
import {storeToRefs} from 'pinia'

const emit = defineEmits(['changeSelectedId'])
const apiStore = useApiStore()
const {apiLoading} = storeToRefs(apiStore);
const tableRef = ref();
const props = defineProps({
  /**
   * 数据获取方法。该方法的返回值暂时仅支持Promise和简单对象
   * 返回简单对象时，对象的格式必须为{total: 0, records: []}
   * 返回Promise时，resolve的格式必须为{total: 0, records: []}
   */
  dataGetter: {
    type: Function,
    default: () => {
      return function () {
        return {
          total: 0,
          records: []
        };
      };
    }
  },
  /**
   * 是否挂载后立即获取数据
   */
  immediately: {
    type: Boolean,
    default: true
  },
  selectId: {
    type: String,
    default: ''
  },
  selectIds: {
    type: Array,
    default: []
  }
})

const state = reactive({
  page: 1,
  limit: 10,
  records: [],
  total: 0,

  loading: false
})
const {page, limit, records, total, loading} = toRefs(state)

watch(() => state.records, (val) => {
  if (val?.length) {
    nextTick(() => {
      if (props.selectId) {
        const selectedRow = val.find((item) => {
          return item.id === props.selectId
        })
        if (selectedRow?.id) {
          emit('changeSelectedId', selectedRow?.id)
        }
        setCurrentRow(selectedRow)
      }
      if (props.selectIds?.length) {
        let initList = []
        val?.map((item) => {
          if (props.selectIds?.filter((v) => v == item.id)?.length) {
            console.log(item)
            initList.push(item)
            emit('changeSelectedId', item.id)
          }
        })
        toggleSelection(initList)
      }
    })
  }
}, {deep: true})


onMounted(() => {
  if (props.immediately) {
    getTableData({page: state.page, limit: state.limit});
  }
})


const getTableData = (event) => {
  let {page, limit} = event
  state.loading = true;
  state.page = page;
  state.limit = limit
  const result = props.dataGetter({
    page: page,
    limit: limit
  });
  if (lodash.isPlainObject(result)) {
    state.total = result.total || 0;
    state.records = result.records || [];
    state.loading = false;
  } else if (result instanceof Promise) {
    result
        .then(res => {
          state.total = res.total || 0;
          state.records = res.records || [];
        })
        .catch(() => {
          state.records = [];
        })
        .finally(() => {
          state.loading = false;
        });
  }
}
const reload = () => {
  getTableData({page: 1, limit: 10});
}
const reloadCurrentPage = () => {
  getTableData({page: state.page, limit: state.limit});
}
const setLoadding = (porps) => {
  state.loading = porps;
}

const clearSelection = () => {
  unref(tableRef).clearSelection();
}

const toggleRowSelection = (val) => {
  unref(tableRef).toggleRowSelection(val);
}
const setCurrentRow = (val) => {
  unref(tableRef).setCurrentRow(val);
}

const toggleSelection = (rows = []) => {
  rows?.forEach((row) => {
    // TODO: improvement typing when refactor table
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-expect-error
    unref(tableRef)?.toggleRowSelection(row, undefined)
  })
}

defineExpose({
  //重新加载
  reload,
  //重新加载（当前页）
  reloadCurrentPage,
  //设置loading
  setLoadding,
  //清除选中
  clearSelection,
  //用于多选表格，切换某一行的选中状态， 如果使用了第二个参数，则可直接设置这一行选中与否
  toggleRowSelection,
  //用于单选表格，设定某一行为选中行， 如果调用时不加参数，则会取消目前高亮行的选中状态。
  setCurrentRow


})
</script>

<style lang="scss" scoped>
.es-table {
  display: flex;
  flex-direction: column;
}

.es-pagination {
  display: flex;
  align-items: center;
  justify-content: end;
}
</style>
